<?php

namespace Aitels\Design;

use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 读取design.xlsx 中的表定义
 *
 * Class ExcelDefinitionProvider
 * @package Aitels\Design
 */
class ExcelDefinitionProvider implements DefinitionProvider

{
    protected $path;

    public function __construct($path)
    {
        $this->path = $path;
    }


    public function provide()
    {
        return $this->read();
    }

    public function read()
    {
        $sheets = $this->getReader()->load($this->path)->getAllSheets();
        $definitions = [];
        foreach ($sheets as $sheet) {
            list($tableModelName,$tableName, $tableZhName, $columns) = $this->extractDefinitionFromSheet($sheet->toArray());
            $definitions[] = compact('tableModelName','tableName', 'tableZhName', 'columns');
        }
        return $definitions;
    }

    public function getReader()
    {
        return IOFactory::createReader('Xlsx')
            ->setLoadAllSheets();
    }

    public function extractDefinitionFromSheet($sheet)
    {
        $tableModelName=$sheet[3][0];
        $tableName = Util::snakeCase($sheet[3][0]);//表英文复数名称
        $tableZhName = $sheet[0][0];//表中文复数名称
        $count = count($sheet);//行数
        $columns = [];
        //字段定义从第十行开始
        for ($i = 9; $i < $count; $i++) {
            $column = $sheet[$i];
            $columns[] = [
                'name' => $column[1],
                'type' => $column[2],
                'param1' => $column[3],
                'param2' => $column[4],
                'primary' => $column[5],
                'index' => $column[6],
                'default' => $column[7],
                'comment' => $column[0] . ($column[8] ? ",$column[8]" : "")
            ];
        }
        return [$tableModelName,$tableName, $tableZhName, $columns];
    }


}